<?php

namespace addons\customform\controller;

use app\common\exception\UploadException;
use app\common\library\Upload;
use think\addons\Controller;
use think\File;

class Test extends Controller
{
    protected $noNeedLogin = ['*'];

    //获取单条配置数据
    public function design_data()
    {
        $id = input("id", 0, "intval");

        $result = db("customform")->where("id", $id)->find();

        if (!$result) {
            return json(['code' => 0, 'msg' => '数据不存在']);
        }

        $result['config'] = json_decode($result['config'], true);

        return json(['code' => 1, "data" => $result]);
    }

    //保存数据
    public function design_save()
    {
        $id = input("id", 0, "intval");

        $result = db("customform")->where("id", $id)->find();

        if (!$result) {
            return json(['code' => 0, 'msg' => '数据不存在']);
        }

        $data = input("data");
        $data = htmlspecialchars_decode($data);
        $data = html_entity_decode($data);

        $rs = db("customform")->where("id", $id)->update(['updatetime' => time(), 'config' => $data]);

        if ($rs) {
            return json(['code' => 1, 'msg' => '保存成功']);
        } else {
            return json(['code' => 0, 'msg' => '保存失败']);
        }
    }

    //附件查询
    public function attachment()
    {
        $keyword  = $this->request->post('keyword', '');
        $page     = $this->request->post('page/d', 1);
        $limit    = $this->request->post('limit/d', 10);
        $mimetype = $this->request->post('mimetype', 'image');

        $where['mimetype'] = ['like', "%{$mimetype}%"];

        if ($keyword) {
            $where['filename'] = ['like', "%{$keyword}%"];
        }

        $list = db('attachment')->where($where)->field('id,url,filename')->order("id desc")->page($page, $limit)->select();

        foreach ($list as $key => $value) {
            $list[$key]['url'] = cdnurl($value['url'], true);
        }

        $total = db('attachment')->where($where)->count();

        return json(['code' => 1, 'data' => ['list' => $list, 'total' => $total]]);
    }

    //用户表单数据查询
    public function edit_data()
    {
        $id = input("id", 0, "intval");

        $result = db("customform_data")->alias("a")->join("customform b", "a.customform_id = b.id")->field("a.*,b.config")->where("a.id", $id)->find();

        if (!$result) {
            return json(['code' => 0, 'msg' => '数据不存在']);
        }

        $result['config'] = json_decode($result['config'], true);

        $result['data'] = json_decode($result['data'], true);

        $result['config']['dataconfig'] = $this->search_add_value($result['config']['dataconfig'], $result['data']);

        return json(['code' => 1, "data" => $result]);
    }

    //更新用户表单数据
    public function save_data()
    {
        $id    = input("id", 0, "intval");
        $data  = input("data/a", [], 'htmlspecialchars');
        $token = input("__token__", '');

        $validate = $this->validate(
            [
                'id'        => $id,
                '__token__' => $token,
            ],
            [
                'id'        => 'require',
                '__token__' => 'require|token',
            ]);
        if (true !== $validate) {
            // 验证失败 输出错误信息
            return json(['code' => 0, 'msg' => $validate, '__token__' => $this->request->token()]);
        }

        $result = db("customform_data")->alias("a")->join("customform b", "a.customform_id = b.id")->field("a.*,b.config_path")->where("a.id", $id)->find();

        if (!$result) {

            return json(['code' => 0, 'msg' => '数据不存在', '__token__' => $this->request->token()]);
        }

        $result['config'] = json_decode(file_get_contents($result['config_path']), true);

        $newdata = [];

        foreach ($data as $key => $value) {
            $newdata[] = ["id" => $key, "value" => $value];
        }

        //查询必须填写的值
        $nempty_list = $this->nempty_value($result['config']['dataconfig']);

        foreach ($nempty_list as $key => $value) {
            //检验数据是否存在
            if (!$this->search_value($newdata, $value)) {
                return json(['code' => 0, 'msg' => $value['config']['label'] . $value['config']['message'], 'data' => $value['id'], '__token__' => $this->request->token()]);
            }
        }

        $rs = db("customform_data")->where('id', $id)->update(['data' => json_encode($newdata), 'updatetime' => time()]);

        if ($rs) {
            return json(['code' => 1, 'msg' => '修改成功', '__token__' => $this->request->token()]);
        } else {
            return json(['code' => 0, 'msg' => '修改失败，请重试', '__token__' => $this->request->token()]);
        }

    }

    //递归赋值数据
    protected function search_add_value($array, $data)
    {
        foreach ($array as $key => $value) {
            if (empty($value['list'])) {
                foreach ($data as $keys => $values) {
                    if ($value['id'] == $values['id']) {
                        $array[$key]['config']['value'] = $values['value'];
                        unset($data[$keys]);
                    }
                }
            } else {
                $array[$key]['list'] = $this->search_add_value($value['list'], $data);
            }
        }

        return $array;
    }

    //检验提交值
    protected function search_value($array, $data)
    {
        $check = false;

        foreach ($array as $key => $value) {
            if ($value['id'] == $data['id']) {
                //正则不为空
                if (($data['config']['regular'] && !preg_match($data['config']['regular'], $value['value'])) || empty($value['value'])) {

                    return false;
                } else {
                    $check = true;
                    continue;
                }
            }
        }

        return $check;
    }

    //查询总数据中不能为空的值
    protected function nempty_value($array)
    {
        $new_array = [];
        foreach ($array as $key => $value) {
            if (empty($value['list'])) {
                if (!empty($value['config']['required'])) {
                    $new_array[] = $value;
                }
            } else {
                $new_array = array_merge($new_array, $this->nempty_value($value['list']));
            }
        }

        return $new_array;
    }

    public function get_theme()
    {
        $page  = $this->request->post('page/d', 1);
        $limit = $this->request->post('limit/d', 10);

        $list  = db("customform")->page($page, $limit)->order('id desc')->select();
        $count = db("customform")->count();

        return json(['code' => 1, 'data' => ['list' => $list, 'count' => $count]]);
    }

    public function api()
    {
        $data = $this->request->post("");

        print_r($data);
    }

    //保存base64图片
    public function save_sign_img()
    {
        $imgdata = $this->request->post('imgdata', '');

        if (!$imgdata) {
            return json(['code' => 0, 'msg' => '图片数据错误']);
        }

        $reg = '/data:image\/(\w+?);base64,(.+)$/si';
        preg_match($reg, $imgdata, $match_result);

        if (!in_array($match_result[1], ['png', 'jpg'])) {
            return json(['code' => 0, 'msg' => '图片数据错误']);
        }

        $file_name = uniqid() . '.' . $match_result[1];

        $wwwpath = DS . 'uploads' . DS . date('Ymd');
        $path    = ROOT_PATH . 'runtime' . DS . 'addons' . DS . 'customform' . $wwwpath;

        if (!is_dir($path)) {
            @mkdir($path, 0755, true);
        }

        file_put_contents($path . DS . $file_name, base64_decode($match_result[2]));

        try {
            $file_info = getimagesize($path . DS . $file_name);

            if (!$file_info || !isset($file_info[0]) || !isset($file_info[1])) {
                throw new UploadException('当前文件不是图片');
            }

            $file_more = [
                "type"     => $file_info['mime'],
                "suffix"   => $match_result[1],
                "name"     => $file_name,
                "size"     => filesize($path . DS . $file_name),
                "tmp_name" => $path . DS . $file_name,
            ];

            $file = (new File($path . DS . $file_name))->setUploadInfo($file_more);
            $file->isTest(true);
            $upload     = new Upload($file);
            $attachment = $upload->upload();
        } catch (UploadException $e) {
            unlink($path . DS . $file_name);
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'data' => $attachment->url]);
    }
}
